/*
 * @Description: 机构管理
 * @Author: DHL
 * @Date: 2022-03-28 14:25:56
 * @LastEditors: DHL
 * @LastEditTime: 2022-08-10 13:21:30
 */

import { defineComponent, computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { assign, cloneDeep } from 'lodash-es'
import { TwTableOptions } from '/@/types/table.d'
import { arraySerializeToStr } from '/@/utils/twUtils'
import { usePermission } from '/@/hooks/web/permission'
import type Node from 'element-plus/es/components/tree/src/model/node'

import { OrganizationModel, OrganizationPageParams } from '/@/api/system/model/organizationModel'
import {
  apiOrganizationLogicDeleteById,
  apiOrganizationResetSearchKey,
  apiOrganizationSearch,
  apiOrganizationUpdateById
} from '/@/api/system/organization'

import organizationForm from './form.vue'
import organizationTree from '../../components/organizationTree.vue'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'

export default defineComponent({
  name: 'Organization',
  components: { organizationForm, organizationTree, Splitpanes, Pane },
  setup(props) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////

    const loading = ref(false)
    const loadingByDel = ref(false)

    // 权限控制
    const { hasPermission } = usePermission()

    /**
     * 表格数据
     */
    const tableData = ref()

    /**
     * 查询表单
     */
    const searchFormRef = ref()

    /**
     * 数据列表
     */
    const tableRef = ref()

    /**
     * 表单
     */
    const formRef = ref()

    /**
     * 是否有选中的行
     */
    const isSelectRows = computed(() => {
      let selectRows: Array<OrganizationModel> = []
      if (tableRef.value) {
        selectRows = tableRef.value.getSelectRows()
      }
      return selectRows.length < 1
    })

    //////////////////////////////////////////////////
    // 查询表单
    //////////////////////////////////////////////////

    const defaultSearchForm = {
      tenantId: '', // 租户ID
      parentOrgId: '', // 父级编码
      code: '', // 机构编码
      name: '', // 机构名称
      iconCls: '', // 机构图标
      address: '', // 机构地址
      orgSeq: 0, // 顺序
      orgType: '', // 机构类型
      creatorId: '', // 创建人ID
      creator: '', // 创建人
      updaterId: '', // 更新人ID
      updater: '', // 更新人
      createDate: '', // 创建时间
      updateDate: '' // 更新时间
    }

    /**
     * 查询表单
     */
    const searchForm = reactive(cloneDeep(defaultSearchForm))

    //////////////////////////////////////////////////
    // 表格
    //////////////////////////////////////////////////

    /**
     * 表格配置
     */
    const tableOptions = reactive<TwTableOptions>({
      id: 'organizationTable',
      sortConfig: {
        defaultSort: [{ field: 'orgSeq', order: 'asc' }]
      },
      columns: [
        { type: 'seq', fixed: 'left', title: '序号', width: 50 },
        { field: 'code', title: '机构编码', sortable: true },
        { field: 'name', title: '机构名称', sortable: true },
        { field: 'orgSeq', title: '顺序', sortable: true, slots: { default: 'orgSeq' } },
        {
          field: 'orgType',
          title: '机构类型',
          sortable: true,
          params: { dict: 'ORGANIZATION_TYPE' }
        },
        { field: 'address', title: '机构地址', sortable: true },
        { field: 'updater', title: '更新人', sortable: true },
        { field: 'updateDate', title: '更新时间', sortable: true },
        { title: '操作', fixed: 'right', width: 110, slots: { default: 'action' } }
      ]
    })

    /**
     * 绑定事件
     */
    const tableEvents = reactive({
      cellDblclick(params: { row: OrganizationModel }) {
        if (hasPermission('ORGANIZATION-VIEW')) {
          handleOpenForm('view', params.row)
        } else {
          ElMessage.warning('无权限访问')
        }
      }
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 查询表格数据函数
     * @param queryParams
     */
    function searchList(queryParams: OrganizationPageParams) {
      loading.value = true
      apiOrganizationSearch(
        assign(queryParams, searchForm, {
          parentOrgId: selectTreeNode.id
        })
      )
        .then((result) => {
          tableData.value = result
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 查询表格数据
     */
    function handleSearch() {
      tableRef.value.handleQuery()
    }

    /**
     * 刷新
     */
    function handleRefresh() {
      orgTreeRef.value.handleSearchTree()
      tableRef.value.handleReload()
    }

    /**
     * 重置
     */
    function handleReset() {
      assign(searchForm, cloneDeep(defaultSearchForm))
      tableRef.value.handleQuery()
    }

    /**
     * 批量删除
     */
    function handleDelete(row?: OrganizationModel) {
      let selectRows: Array<OrganizationModel> = []

      if (row) {
        selectRows = [row]
      } else {
        selectRows = tableRef.value.getSelectRows()
      }

      if (selectRows.length === 0) {
        ElMessage.warning('请选择需要删除的数据')
        return
      }

      ElMessageBox.confirm(`此操作将删除${selectRows.length}条记录, 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          loading.value = true
          const ids = arraySerializeToStr(selectRows, 'id')
          apiOrganizationLogicDeleteById(ids)
            .then((result) => {
              if (result?.success) {
                handleRefresh()
                ElMessage.success(result.message)
              } else {
                ElMessage.error(result?.message)
              }
            })
            .catch(() => { })
            .finally(() => {
              loading.value = false
            })
        })
        .catch(() => {
          ElMessage.info('删除被取消了')
        })
    }

    /**
     * 弹出表单
     */
    function handleOpenForm(action: string, row?: OrganizationModel) {
      const parentOrgName = orgTreeRef.value.getSelectNodeParentName()

      formRef.value.handleOpen(action, row, {
        parentOrgId: selectTreeNode.id,
        parentOrgName: parentOrgName.join(' - ')
      })
    }

    /**
     * 重置SearchKey
     */
    function handleResetSearchKey() {
      loadingByDel.value = true
      apiOrganizationResetSearchKey()
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .finally(() => {
          loadingByDel.value = false
        })
    }

    /**
     * 机构更新
     */
    function handleUpdateById(row: OrganizationModel) {
      loading.value = true
      apiOrganizationUpdateById(row)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)
            handleRefresh()
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    //////////////////////////////////////////////////
    // 机构树
    //////////////////////////////////////////////////
    const orgTreeRef = ref()

    /**
     * 选中的树节点
     */
    let selectTreeNode: any = {}

    /**
     * 节点点击事件
     */
    function handleNodeClick(treeNode?: Node) {
      selectTreeNode = treeNode ? treeNode : {}
      handleSearch()
    }

    /**
     * 机构数刷新
     */
    function handleTreeSearch() { }

    //////////////////////////////////////////////////
    // 生命周期
    //////////////////////////////////////////////////
    onMounted(() => { })

    return {
      loading,
      loadingByDel,
      tableData,
      searchFormRef,
      tableRef,
      formRef,
      searchForm,
      tableOptions,
      tableEvents,
      isSelectRows,
      orgTreeRef,
      searchList,
      handleSearch,
      handleRefresh,
      handleReset,
      handleDelete,
      handleOpenForm,
      handleNodeClick,
      handleTreeSearch,
      handleResetSearchKey,
      handleUpdateById
    }
  }
})
